package com.hotau.geo;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.activeandroid.Application;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.Geometry;
import com.baidu.mapapi.map.Graphic;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.MyLocationOverlay.LocationMode;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PoiOverlay;
import com.baidu.mapapi.map.PopupClickListener;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.map.Symbol.Stroke;
import com.baidu.mapapi.map.TextItem;
import com.baidu.mapapi.map.TextOverlay;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKShareUrlResult;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.hotau.HotauActivity;
import com.hotau.R;
import com.hotau.framework.SearchBarVisible;
import com.hotau.seller.SellerDetailFragment;


public class GeoMapFragment extends Fragment implements SearchBarVisible{

	private String TAG = "GeoMapActivity";

	private enum E_BUTTON_TYPE {
		LOC, COMPASS, FOLLOW
	}

	private E_BUTTON_TYPE mCurBtnType;

	// 定位相关
	LocationClient mLocClient;
	LocationData locData = null;
	
	// 定位图层
	MyLocationOverlay myLocationOverlay = null;
	// 弹出泡泡图层
	private PopupOverlay pop = null;// 弹出泡泡图层，浏览节点时使用
	private TextView popupText = null;// 泡泡view
	private View viewCache = null;

	private MKSearch mSearch = null; // 搜索模块，也可去掉地图模块独立使用
	// 保存搜索结果地址
	private String currentAddr = null;

	// 地图相关，使用继承MapView的MyLocationMapView目的是重写touch事件实现泡泡处理
	// 如果不处理touch事件，则无需继承，直接使用MapView即可
	private MyLocationMapView mMapView = null; // 地图View
	private MapController mMapController = null;

	Button requestLocButton = null;
	boolean isRequest = false;// 是否手动触发请求定位
	boolean isFirstLoc = true;// 是否首次定位

	// 搜索关键字
	private String searchKey = "餐馆";
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		requestLocButton = (Button) getActivity().findViewById(R.id.button1);
		mCurBtnType = E_BUTTON_TYPE.LOC;
		requestLocButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				switch (mCurBtnType) {
					case LOC:
						// 手动定位请求
						requestLocClick();
						break;
					case COMPASS:
						myLocationOverlay.setLocationMode(LocationMode.NORMAL);
						requestLocButton.setText("定位");
						mCurBtnType = E_BUTTON_TYPE.LOC;
						break;
					case FOLLOW:
						myLocationOverlay.setLocationMode(LocationMode.COMPASS);
						requestLocButton.setText("罗盘");
						mCurBtnType = E_BUTTON_TYPE.COMPASS;
						break;
				}
			}
		});

		RadioGroup group = (RadioGroup)  getActivity().findViewById(R.id.radioGroup);
		group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId == R.id.defaulticon) {
					modifyLocationOverlayIcon(null);
				} else if (checkedId == R.id.poishare) {
					sharePoi();
				} else if (checkedId == R.id.addrshare) {
					shareAddr();
				}
			}
		});

		// 地图初始化
		mMapView = (MyLocationMapView)  getActivity().findViewById(R.id.bmapView);
		mMapController = mMapView.getController();
		mMapView.getController().setZoom(19);
		mMapView.getController().enableClick(true);
		mMapView.setBuiltInZoomControls(true);
		// 创建 弹出泡泡图层
		createPaopao();

		// 初始化搜索模块，注册搜索事件监听
		mSearch = new MKSearch();
		mSearch.init(Application.getInstance().getMapManager(),
				new MKSearchListener() {
					@Override
					public void onGetPoiDetailSearchResult(int type, int error) {
					}

					/**
					 * 在此处理poi搜索结果 , 用poioverlay 显示
					 */
					public void onGetPoiResult(MKPoiResult res, int type, int error) {
						// 错误号可参考MKEvent中的定义
						if (error != 0 || res == null) {
							Toast.makeText(getActivity(), "抱歉，未找到结果", Toast.LENGTH_LONG).show();
							return;
						}
						
						// 将地图移动到第一个POI中心点
						if (res.getCurrentNumPois() > 0) {
							// 将poi结果显示到地图上
							PoiOverlay poiOverlay = new PoiOverlay(getActivity(), mMapView){
								@Override
								protected boolean onTap(int i) {
									MKPoiInfo info = getPoi(i);
									currentAddr = info.address;
									
									SellerDetailFragment fragment = new SellerDetailFragment();
									HotauActivity baseAct = (HotauActivity)getActivity();
									baseAct.pushFragment("商铺信息", fragment);
									//mSearch.poiDetailShareURLSearch(info.uid);
									return true;
								}
							};
							poiOverlay.setData(res.getAllPoi());
							mMapView.getOverlays().clear();
							mMapView.getOverlays().add(poiOverlay);
							mMapView.refresh();
							
							// 当ePoiType为2（公交线路）或4（地铁线路）时， poi坐标为空
							for (MKPoiInfo info : res.getAllPoi()) {
								if (info.pt != null) {
									mMapView.getController().animateTo(info.pt);
									break;
								}
							}
						}
					}

					public void onGetDrivingRouteResult(
							MKDrivingRouteResult res, int error) {
					}

					public void onGetTransitRouteResult(
							MKTransitRouteResult res, int error) {
					}

					public void onGetWalkingRouteResult(
							MKWalkingRouteResult res, int error) {
					}

					/**
					 * 在此处理反地理编结果
					 */
					public void onGetAddrResult(MKAddrInfo res, int error) {
						// 错误号可参考MKEvent中的定义
						if (error != 0 || res == null) {
							Toast.makeText( getActivity(), "抱歉，未找到结果", Toast.LENGTH_LONG).show();
							return;
						}
						AddrShareOverlay addrOverlay = new AddrShareOverlay(
								getResources().getDrawable(R.drawable.icon_marka), mMapView, res);
						mMapView.getOverlays().clear();
						mMapView.getOverlays().add(addrOverlay);
						mMapView.refresh();

					}

					public void onGetBusDetailResult(MKBusLineResult result, int iError) {
					}

					@Override
					public void onGetSuggestionResult(MKSuggestionResult res, int arg1) {
					}

					@Override
					public void onGetShareUrlResult(MKShareUrlResult result,
							int type, int error) {
						// 分享短串结果
						Intent it = new Intent(Intent.ACTION_SEND);
						it.putExtra(Intent.EXTRA_TEXT, "您的朋友通过百度地图SDK与您分享一个位置: " + currentAddr + " -- " + result.url);
						it.setType("text/plain");
						startActivity(Intent.createChooser(it, "将短串分享到"));

					}
				});

		// 定位初始化
		mLocClient = new LocationClient(getActivity());
		locData = new LocationData();
		mLocClient.registerLocationListener(new BDLocationListener(){
			@Override
			public void onReceiveLocation(BDLocation location) {
				if (location == null)
					return;

				locData.latitude = location.getLatitude();
				locData.longitude = location.getLongitude();
				// 如果不显示定位精度圈，将accuracy赋值为0即可
				locData.accuracy = location.getRadius();
				// 此处可以设置 locData的方向信息, 如果定位 SDK 未返回方向信息，用户可以自己实现罗盘功能添加方向信息。
				locData.direction = location.getDerect();
				// 更新定位数据
				myLocationOverlay.setData(locData);
				// 更新图层数据执行刷新后生效
				addCustomElements();
				// 是手动触发请求或首次定位时，移动到定位点
				if (isRequest || isFirstLoc) {
					// 移动地图到定位点
					Log.d("LocationOverlay", "receive location, animate to it");
					mMapController.animateTo(new GeoPoint(
							(int) (locData.latitude * 1e6),
							(int) (locData.longitude * 1e6)));
					isRequest = false;
					myLocationOverlay.setLocationMode(LocationMode.FOLLOWING);
					requestLocButton.setText("跟随");
					mCurBtnType = E_BUTTON_TYPE.FOLLOW;
				}
				// 首次定位完成
				isFirstLoc = false;
			}

			public void onReceivePoi(BDLocation poiLocation) {
				if (poiLocation == null) {
					return;
				}
			}
		});
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		mLocClient.setLocOption(option);
		mLocClient.start();
		myLocationOverlay=new MyLocationOverlay(mMapView) {
			@Override
			protected boolean dispatchTap() {
				// TODO Auto-generated method stub
				// 处理点击事件,弹出泡泡
				popupText.setBackgroundResource(R.drawable.popup);
				popupText.setText("我的位置");
				pop.showPopup(GeoBMapUtil.getBitmapFromView(popupText),
						new GeoPoint((int) (locData.latitude * 1e6),
								(int)(locData.longitude * 1e6)), 8);
				return true;
			}
		};
		// 设置定位数据
		myLocationOverlay.setData(locData);
		// 添加定位图层
		mMapView.getOverlays().add(myLocationOverlay);
		
		myLocationOverlay.enableCompass();
		mMapView.refresh();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.geo_map, container, false);
	}
	
	/**
	 * 手动触发一次定位请求
	 */
	public void requestLocClick() {
		isRequest = true;
		mLocClient.requestLocation();
		Toast.makeText(getActivity(), "正在定位……", Toast.LENGTH_SHORT).show();
	}

	/**
	 * 修改位置图标
	 * 
	 * @param marker
	 */
	public void modifyLocationOverlayIcon(Drawable marker) {
		// 当传入marker为null时，使用默认图标绘制
		myLocationOverlay.setMarker(marker);
		// 修改图层，需要刷新MapView生效
		mMapView.refresh();
	}

	/**
	 * 使用ItemizevOvelray展示反地理编码点位置，当该点被点击时发起短串请求.
	 * 
	 */
	private class AddrShareOverlay extends ItemizedOverlay {

		private MKAddrInfo addrInfo;

		public AddrShareOverlay(Drawable defaultMarker, MapView mapView, MKAddrInfo addrInfo) {
			super(defaultMarker, mapView);
			this.addrInfo = addrInfo;
			addItem(new OverlayItem(addrInfo.geoPt, addrInfo.strAddr, addrInfo.strAddr));
		}

		@Override
		public boolean onTap(int index) {
			currentAddr = addrInfo.strAddr;
			mSearch.poiRGCShareURLSearch(addrInfo.geoPt, "分享地址", addrInfo.strAddr);
			return true;
		}
	}

	/**
	 * 创建弹出泡泡图层
	 */
	public void createPaopao() {
		viewCache = getActivity().getLayoutInflater().inflate(R.layout.geo_text_view, null);
		popupText = (TextView) viewCache.findViewById(R.id.textcache);
		// 泡泡点击响应回调
		PopupClickListener popListener = new PopupClickListener() {
			@Override
			public void onClickedPopup(int index) {
				Log.v("click", "clickapoapo");
			}
		};
		pop = new PopupOverlay(mMapView, popListener);
		MyLocationMapView.pop = pop;
	}

	public void sharePoi() {
		// 发起poi搜索
		mSearch.poiSearchNearBy(searchKey,
				new GeoPoint((int) (locData.latitude * 1e6),
						(int) (locData.longitude * 1e6)), 500);
		Toast.makeText(getActivity(), "在我的位置搜索 " + searchKey, Toast.LENGTH_SHORT).show();
	}

	public void shareAddr() {
		GeoPoint currentPoint = new GeoPoint((int) (locData.latitude * 1e6),
				(int) (locData.longitude * 1e6));
		// 发起反地理编码请求
		mSearch.reverseGeocode(currentPoint);
		Toast.makeText(getActivity(),
				String.format("搜索位置： %f，%f",
						(currentPoint.getLatitudeE6() * 1E-6),
						(currentPoint.getLongitudeE6() * 1E-6)),
				Toast.LENGTH_SHORT).show();
	}

	/**
	 * 添加点、线、多边形、圆、文字
	 */
	public void addCustomElements() {
		GraphicsOverlay graphicsOverlay = new GraphicsOverlay(mMapView);
		mMapView.getOverlays().add(graphicsOverlay);
		// 添加圆
		graphicsOverlay.setData(drawCircle());
		// 绘制文字
		TextOverlay textOverlay = new TextOverlay(mMapView);
		mMapView.getOverlays().add(textOverlay);
		textOverlay.addText(drawText());
		// 执行地图刷新使生效
		mMapView.refresh();
	}

	/**
	 * 绘制圆，该圆随地图状态变化
	 * 
	 * @return 圆对象
	 */
	public Graphic drawCircle() {

		int lat = (int) (locData.latitude * 1e6);
		int lon = (int) (locData.latitude * 1e6);

		Log.i(TAG, "当前X坐标：" + locData.latitude * 1e6 + "，当前Y坐标：" + locData.latitude * 1e6);
		GeoPoint pt1 = new GeoPoint(lat, lon);
		// 构建圆
		Geometry circleGeometry = new Geometry();
		// 设置圆中心点坐标和半径
		circleGeometry.setCircle(pt1, 2500);
		// 设置样式
		Symbol circleSymbol = new Symbol();
		Symbol.Color circleColor = circleSymbol.new Color();
		circleColor.red = 0;
		circleColor.green = 255;
		circleColor.blue = 0;
		circleColor.alpha = 126;
		circleSymbol.setSurface(circleColor, 1, 3, new Stroke(3, circleSymbol.new Color(0xFFFF0000)));
		// 生成Graphic对象
		return new Graphic(circleGeometry, circleSymbol);
	}

	/**
	 * 绘制文字，该文字随地图变化有透视效果
	 * 
	 * @return 文字对象
	 */
	public TextItem drawText() {
		int lat = (int) (locData.latitude * 1E6);
		int lon = (int) (locData.latitude * 1E6);
		// 构建文字
		TextItem item = new TextItem();
		// 设置文字位置
		item.pt = new GeoPoint(lat, lon);
		// 设置文件内容
		item.text = "百度地图SDK";
		// 设文字大小
		item.fontSize = 40;
		Symbol symbol = new Symbol();
		Symbol.Color bgColor = symbol.new Color();
		// 设置文字背景色
		bgColor.red = 0;
		bgColor.blue = 0;
		bgColor.green = 255;
		bgColor.alpha = 50;

		Symbol.Color fontColor = symbol.new Color();
		// 设置文字着色
		fontColor.alpha = 255;
		fontColor.red = 0;
		fontColor.green = 0;
		fontColor.blue = 255;
		// 设置对齐方式
		item.align = TextItem.ALIGN_CENTER;
		// 设置文字颜色和背景颜色
		item.fontColor = fontColor;
		item.bgColor = bgColor;
		return item;
	}

	@Override
	public void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	public void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	public void onDestroy() {
		// 退出时销毁定位
		if (mLocClient != null)
			mLocClient.stop();
		mMapView.destroy();
		super.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mMapView.onSaveInstanceState(outState);

	}
}

/**
 * 继承MapView重写onTouchEvent实现泡泡处理操作
 * 
 * @author hejin
 * 
 */
class MyLocationMapView extends MapView {
	static PopupOverlay pop = null;// 弹出泡泡图层，点击图标使用

	public MyLocationMapView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public MyLocationMapView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MyLocationMapView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (!super.onTouchEvent(event)) {
			// 消隐泡泡
			if (pop != null && event.getAction() == MotionEvent.ACTION_UP)
				pop.hidePop();
		}
		return true;
	}

}
